package wework

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"gogogo/util/client/redis"
	"io/ioutil"
	"log"
	"net/http"
)

func GetAccessToken(corpId string, corpSecret string) (accessToken string, err error) {

	// 首先从redis中获取accessToken值
	token, err := getAccessTokenFromRedis(corpId, corpSecret)
	if err == nil && token != "" {
		return token, nil
	}
	// 如果缓存中不存在，从企微获取，然后存储到缓存中
	url := fmt.Sprintf("%s/gettoken?corpid=%s&corpsecret=%s", WEWORK_HOST, corpId, corpSecret)
	resp, err := http.Get(url)
	if err != nil {
		log.Printf("GetAccessToken error. %v", err.Error())
		return
	}
	defer resp.Body.Close()
	log.Printf("status code is %d", resp.StatusCode)
	bytes, err := ioutil.ReadAll(resp.Body)
	var response GetTokenResponse
	json.Unmarshal(bytes, &response)
	fmt.Println(response.ToString())
	if SUCCESS == response.ErrCode {
		setAccessTokenToRedis(corpId, corpSecret, response.AccessToken)
		return response.AccessToken, nil
	}
	return "", errors.New(response.ErrMsg)
}

func setAccessTokenToRedis(corpId, corpSecret, accessToken string) {
	key := getKey(corpId, corpSecret)
	redis.Set(key, accessToken, "EX", 7200)
}

func getAccessTokenFromRedis(corpId, corpSecret string) (accessToken string, err error) {
	key := getKey(corpId, corpSecret)
	accessToken, err = redis.GetString(key)
	return
}

func getKey(corpId, corpSecret string) string {
	sum := md5.Sum([]byte(fmt.Sprintf("%s_%s", corpId, corpSecret)))
	return "access_token:" + fmt.Sprintf("%x", sum)
}